import bodyParser from 'body-parser';
import compression from 'compression';
import config from 'config';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import PrettyError from 'pretty-error';
import process from 'process';

import jwt from './middlewares/jwt';
import initSession from './middlewares/session';
import db from './src/db';
import {setup as RouteSetup} from './src/decorator/router';
import startJob from './src/job/';

export default function setup(initJob: boolean) {
    const app = express();
    if (process.env.NODE_ENV !== 'production') {
        app.use(cors({origin: true, credentials: true}));
    }
    app.use(compression());
    app.use(cookieParser());
    app.use(bodyParser.json({limit: '10mb'}));
    app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));

    db.init(initJob && startJob);
    initSession(app);
    jwt(app);
    RouteSetup(app);
    const {port}: any = config;

    const pe = new PrettyError();
    pe.skipNodeFiles();
    pe.skipPackage('express');

    const pid = process.pid;

    app.listen(port, () => {
        console.log(`${pid}:The server is running at http://localhost:${port}`);
    });
}
